#!/usr/bin/env python3
"""
航班管理系统测试运行器
简化版测试脚本，直接运行所有测试
"""

import os
import sys
import subprocess
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

def run_simple_tests():
    """运行简化测试"""
    print("🚀 开始航班管理系统测试")
    print("=" * 50)
    
    # 检查Python环境
    print("📋 检查Python环境...")
    result = subprocess.run([sys.executable, "--version"], capture_output=True, text=True)
    print(f"✅ Python版本: {result.stdout.strip()}")
    
    # 检查依赖
    print("\n📦 检查依赖...")
    required_packages = ["fastapi", "sqlalchemy", "pytest", "httpx"]
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
            print(f"✅ {package} 已安装")
        except ImportError:
            print(f"❌ {package} 未安装")
            missing_packages.append(package)
    
    if missing_packages:
        print(f"\n📥 安装缺失的依赖: {', '.join(missing_packages)}")
        subprocess.run([sys.executable, "-m", "pip", "install"] + missing_packages)
    
    # 创建测试数据库
    print("\n🗄️ 创建测试数据库...")
    test_db_path = project_root / "test.db"
    if test_db_path.exists():
        test_db_path.unlink()
    
    # 运行数据库初始化
    try:
        from tests.database import Base, engine
        Base.metadata.create_all(bind=engine)
        print("✅ 测试数据库创建成功")
    except Exception as e:
        print(f"❌ 数据库创建失败: {e}")
        return False
    
    # 运行测试
    print("\n🧪 运行单元测试...")
    try:
        # 逐个运行测试文件
        test_files = [
            "tests/test_flight.py",
            "tests/test_passenger.py", 
            "tests/test_booking.py",
            "tests/test_report.py"
        ]
        
        total_tests = 0
        passed_tests = 0
        
        for test_file in test_files:
            if os.path.exists(test_file):
                print(f"\n📄 运行 {test_file}...")
                result = subprocess.run([
                    sys.executable, "-m", "pytest", test_file, 
                    "-v", "--tb=short"
                ], capture_output=True, text=True)
                
                if result.stdout:
                    print(result.stdout)
                if result.stderr and "warning" not in result.stderr.lower():
                    print("错误:", result.stderr)
                
                if result.returncode == 0:
                    passed_tests += 1
                    print(f"✅ {test_file} 测试通过")
                else:
                    print(f"❌ {test_file} 测试失败")
                
                total_tests += 1
            else:
                print(f"⚠️ {test_file} 不存在，跳过")
        
        print(f"\n📊 测试统计: {passed_tests}/{total_tests} 个测试文件通过")
        
        # 运行API集成测试
        print("\n🔗 运行API集成测试...")
        try:
            from app.main import app
            from fastapi.testclient import TestClient
            
            client = TestClient(app)
            
            # 测试健康检查端点
            response = client.get("/")
            if response.status_code == 200:
                print("✅ API服务启动正常")
            else:
                print("❌ API服务启动异常")
            
            # 测试航班列表
            response = client.get("/flights/")
            if response.status_code == 200:
                print("✅ 航班列表API正常")
            else:
                print("❌ 航班列表API异常")
            
            # 测试乘客列表
            response = client.get("/passengers/")
            if response.status_code == 200:
                print("✅ 乘客列表API正常")
            else:
                print("❌ 乘客列表API异常")
            
            print("✅ API集成测试完成")
            
        except Exception as e:
            print(f"⚠️ API集成测试部分失败: {e}")
        
        return passed_tests == total_tests
        
    except Exception as e:
        print(f"❌ 测试运行失败: {e}")
        return False

def cleanup():
    """清理测试文件"""
    test_files = ["test.db", "test.db-journal"]
    for file in test_files:
        file_path = Path(file)
        if file_path.exists():
            file_path.unlink()
            print(f"🧹 清理了 {file}")

def main():
    """主测试流程"""
    try:
        success = run_simple_tests()
        
        print("\n" + "=" * 50)
        if success:
            print("🎉 所有测试通过！航班管理系统已准备就绪")
            print("\n📋 系统功能验证:")
            print("✅ 航班管理模块")
            print("✅ 乘客管理模块") 
            print("✅ 预订管理模块")
            print("✅ 统计报表模块")
            print("✅ API接口测试")
            print("✅ 数据库连接")
        else:
            print("❌ 部分测试未通过，请检查具体错误信息")
        
        return 0 if success else 1
        
    finally:
        cleanup()

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)